package com.furkid.service.service.impl;

import com.furkid.service.common.exception.BizException;
import com.furkid.service.constant.HttpStatus;
import com.furkid.service.domain.pet.Pet;
import com.furkid.service.domain.pet.PetDisease;
import com.furkid.service.mapper.PetHealthMapper;
import com.furkid.service.mapper.PetMapper;
import com.furkid.service.service.IHealthService;
import com.furkid.service.web.context.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IHealthServiceImpl implements IHealthService {
    @Autowired
    PetHealthMapper petHealthMapper;

    @Autowired
    PetMapper petMapper;

    @Override
    public List<PetDisease> petDiseaseListByPetId(Long petId) {
        checkPetIdIsExist(petId);

        return petHealthMapper.petDiseaseListByPetId(petId);
    }

    @Override
    public void addPetDisease(PetDisease petDisease) {
        checkPetIdIsExist(petDisease.getPetId());
        int ret = petHealthMapper.addPetOneDisease(petDisease);
        if (ret == 0) {
            throw new BizException(HttpStatus.Error, "添加宠物病情失败，未知错误!!!");
        }
    }

    @Override
    public void updatePetDisease(PetDisease petDisease) {
        checkPetIdIsExist(petDisease.getPetId());
        int ret = petHealthMapper.updateOnePetDisease(petDisease);
        if (ret == 0) {
            throw new BizException(HttpStatus.Error, "更新宠物病情失败，未知错误!!!");
        }
    }

    @Override
    public void deletePetDisease(Long id, Long petId) {
        checkPetIdIsExist(petId);

        if (petHealthMapper.deleteOnePetDisease(id, petId) == 0) {
            throw new BizException(HttpStatus.Error, "删除宠物病情失败，未知错误!!!");
        }
    }

    private void checkPetIdIsExist(Long petId) {
        if (petId == null || petId == 0) {
            throw new BizException(HttpStatus.Error, "宠物ID错误，无法查询!!!");
        }

        Pet pet = petMapper.searchPetById(UserContext.getUserId(), petId);
        if (pet == null) {
            throw new BizException(HttpStatus.Error, "用户没有该宠物，无法查询!!!");
        }
    }
}
